<script setup lang="ts">
  import GoodTypesModal from './GoodTypesModal.vue'
  import { ElDivider } from 'element-plus'
  import { h, ref } from 'vue'
  import { GoodTypeFeeStandard, SelectedGoodType } from '../../types'
  import { HMessageBox } from '@/components/common/message'
  import infoTip from '@/config/info-tip'

  defineOptions({
    name: 'ChargeStandardsByGoodType',
  })

  const drawerVisible = ref(false)
  const spacer = h(ElDivider, {
    direction: 'vertical',
    style: 'display: flex; align-items: center;',
  })
  const selectedGoodTypeIds = ref<Array<string>>([])
  const goodTypes = ref<Array<GoodTypeFeeStandard>>([])
  const removeFeeStandardIds = ref<Array<string>>([])

  // 支付网点费用（用于给所有产品都填充上去）
  const allPayNetworkFee = ref('0')

  const updateSelectedGoodTypeIds = () => {
    selectedGoodTypeIds.value = goodTypes.value.map((item) => item.level2TypeId)
  }

  const handleSelectGoodType = async (selectGoodTypes: Array<SelectedGoodType>) => {
    selectGoodTypes.forEach((selectType) => {
      if (!goodTypes.value.map((type) => type.level2TypeId).includes(selectType.typeId)) {
        goodTypes.value.push({
          level1TypeId: '',
          level2TypeId: selectType.typeId,
          level3TypeId: '',
          name: selectType.typeName,
          id: '',
          payNetworkFee: allPayNetworkFee.value,
        })
      }
    })
    updateSelectedGoodTypeIds()
  }

  const handleDelClick = (goodType: GoodTypeFeeStandard) => {
    const index = goodTypes.value.findIndex((type) => type.level2TypeId === goodType.level2TypeId)
    if (index !== -1) {
      if (goodTypes.value[index].id) {
        removeFeeStandardIds.value.push(goodTypes.value[index].id)
      }
      goodTypes.value.splice(index, 1)
    }
    updateSelectedGoodTypeIds()
  }

  const handleRemoveGoodTypeByIds = (typeIds: Array<string>) => {
    typeIds.forEach((id) => {
      const index = goodTypes.value.findIndex((type) => type.level2TypeId === id)
      if (index !== -1) {
        if (goodTypes.value[index].id) {
          removeFeeStandardIds.value.push(goodTypes.value[index].id)
        }
        goodTypes.value.splice(index, 1)
      }
    })
    updateSelectedGoodTypeIds()
  }

  defineExpose({
    getList: () => {
      const result: OrderAPIRequest.GoodSettleForm['programmeFeeVos'] = []
      const isNoFillPayNetworkFee = goodTypes.value.some((item) => item.payNetworkFee === '')

      if (isNoFillPayNetworkFee) {
        HMessageBox.error(infoTip.order.goodSettle.noFillPayNeyworkPrice)
        return
      }

      goodTypes.value.forEach((goodType) => {
        result.push({
          goodsId: '',
          goodsName: '',
          goodsOneTypeId: goodType.level1TypeId,
          goodsTwoTypeId: goodType.level2TypeId,
          goodsThreeTypeId: goodType.level3TypeId,
          goodsSpecId: '',
          id: goodType.id || '',
          payNetworkFee: String(goodType.payNetworkFee),
        })
      })

      return result
    },
    setList: (_list: OrderGoodSettleDetail['programmeFeeVos']) => {
      goodTypes.value = _list.map((item) => {
        return {
          name: item.goodsTwoType,
          level1TypeId: '',
          level2TypeId: item.goodsTwoTypeId || '',
          level3TypeId: '',
          payNetworkFee: String(item.payNetworkFee) || '0',
          id: item.id,
        }
      })
      updateSelectedGoodTypeIds()
    },
    getRemovedFeeStandardIds: () => {
      return [...removeFeeStandardIds.value]
    },
    clearList: () => {
      goodTypes.value.length = 0
      removeFeeStandardIds.value.length = 0
    },
    setPayNetworkPrice: (price: string) => {
      allPayNetworkFee.value = price
      goodTypes.value.forEach((item, index) => {
        goodTypes.value[index].payNetworkFee = price
      })
    },
  })
</script>

<template>
  <el-table :border="true" height="100%" :data="goodTypes">
    <template #empty>
      <div class="empty-wrapper">
        <div class="text"> 暂无数据 </div>
        <div class="btn-wrapper">
          <h-link @click="drawerVisible = true">选择产品分类</h-link>
        </div>
      </div>
    </template>
    <!-- 选择 -->
    <el-table-column type="index" width="50" fixed="left" :align="'center'" label="序号" />

    <!-- 产品分类 -->
    <el-table-column label="产品分类" prop="name" min-width="200" />

    <!-- 支付网点费用 -->
    <el-table-column label="支付网点费用" width="200">
      <template #default="{ row }">
        <el-input
          placeholder="请输入支付网点费用"
          :model-value="row.payNetworkFee"
          disabled
        ></el-input>
      </template>
    </el-table-column>

    <!-- 操作 -->
    <el-table-column label="操作" fixed="right" width="100">
      <template #default="{ row, $index }">
        <el-space :size="0" :spacer="spacer">
          <h-link type="error" @click="handleDelClick(row)">删除</h-link>
          <h-link v-if="$index === 0" @click="drawerVisible = true">添加</h-link>
        </el-space>
      </template>
    </el-table-column>

    <good-types-modal
      v-model:visible="drawerVisible"
      :default-selected-ids="selectedGoodTypeIds"
      @confirm="handleSelectGoodType"
      @remove="handleRemoveGoodTypeByIds"
    >
    </good-types-modal>
  </el-table>
</template>

<style scoped lang="scss">
  :deep(.el-table__empty-block) {
    height: unset !important;

    .el-table__empty-text {
      width: 100%;

      .empty-wrapper {
        position: relative;

        .btn-wrapper {
          position: absolute;
          right: 50px;
          top: 50%;
          transform: translate(50%, -50%);
          height: 16px;
          display: flex;
          align-items: center;
        }
      }
    }
  }

  .pay-network-fee-table-cell-header {
    display: flex;
    column-gap: 5px;
    align-items: center;

    .multiple_btn {
      height: 14px;
      line-height: 14px;
    }
  }
</style>
